package logic.common;

import java.util.Collection;
import java.util.LinkedList;

import logic.common.player.Player;
import logic.common.team.Team;
import main.listeners.ListenerContainer;
import main.listeners.ListenerKeeper;

public class Squad implements ListenerKeeper {
	
	public static final int MAX_SQUAD_SIZE = 4;
		
	private LinkedList<Player> members;
	private Team team;
	private ListenerContainer listeners;
	private int index;
	
	public Squad(Team team, int index) {
		this.team = team;
		this.index = index;
		
		members = new LinkedList<Player>();
		listeners = new ListenerContainer(SquadListener.class);
	}
	
	public void addSquadListener(SquadListener l) { listeners.addListener(l); }
	
	public void removeSquadListener(SquadListener l) { listeners.removeListener(l); }
	
	public void addMember(Player newMember) {
		assert(!members.contains(newMember));
		assert(!isFull());
		assert(newMember.getTeam() == team);
		
		members.add(newMember);
		updateListeners();
		
		if(isFull()) team.removeFromEmptySquad(this);
	}
	
	public void removeMember(Player member) {
		assert(members.contains(member));
		
		members.remove(member);
		updateListeners();
		
		team.pushNoneEmptySquad(this);
	}
	
	public boolean isFull() { return members.size() == MAX_SQUAD_SIZE; }
	
	public boolean isEmpty() { return members.isEmpty(); }
	
	public Collection<Player> getMembers() { return members; }
	
	private void updateListeners() {
		listeners.callMethod(SquadListener.SQUADCHANGED, new SquadChangedEvent(this));
	}
	
	@Override
	public int hashCode() { return index; }
	
	@Override
	public ListenerContainer getListenerContainer(Class<?> listenerClass) {
		if(listenerClass == SquadListener.class) return listeners;
		return null;
	}
	
	public Team getTeam() { return team; }
	
	public void applyNewMembers(Collection<Player> newMembers) {
		while(!isEmpty()) {
			members.element().leaveSquad();
		}
		
		for(Player player : newMembers) {
			player.joinSquad(this);
		}
	}
}